public without sharing class CaseToWorkOrderHandler {
	///回写技术服务申请
	public static void backToServicePlan(List<Case> list_new){

		Map<String ,String> techMap = new Map<String,String>();
		Map<String,String >  tmMap = new Map<String,String>();
		Map<String,String> cStatusMap = new Map<String,String>();
		List<TechnicalServicesApplicationForm__c>tList = new List<TechnicalServicesApplicationForm__c>();
		for(Case c : list_new){
			
			if( (c.Status == '已分配' || c.Status == '关闭') && c.Status != null  ){
				if(c.TechnicalServicesApplicationNum__c != null){
					techMap.put(c.TechnicalServicesApplicationNum__c, c.Status);
					tList.add(new TechnicalServicesApplicationForm__c(Id=c.TechnicalServicesApplicationNum__c,ServiceRequestDeliveryStatus__c=c.Status));
				}else if(c.InstallationApply__c != null ){
					tmMap.put(c.Id ,c.InstallationApply__c);
					cStatusMap.put(c.InstallationApply__c, c.Status);
				}	
			}
		}
		System.debug('backToServicePlan==>'+tmMap);
		if(tmMap.keySet().size() == 0 ) return;
		Map<String,String > resMap  = new Map<String,String >();
		for (InstallationApply__c ina:[select Id ,TechnicalServiceApplication__c from InstallationApply__c where Id in:tmMap.values() and TechnicalServiceApplication__c != null  ] ) {			
			resMap.put (ina.TechnicalServiceApplication__c,cStatusMap.get(ina.Id ));

		}
		for (String k  : resMap.keyset()) {
			tList.add(new TechnicalServicesApplicationForm__c(Id=k ,ServiceRequestDeliveryStatus__c=resMap.get(k)));
		}

		if(tList.size()  > 0) update tList;

	}
	//非现场处理打勾,关闭个案
	public static void autoCloseCase(List<Case> list_new ,Map<Id,Case> oldMap){

		Map<Id,Case> mapCase = new Map<Id,Case>();
		for (Case c : list_new ) {
			Case oldc = oldMap.get(c.Id);
			if(c.TelDealComplete__c == true &&  oldc.Status != '关闭' && oldc.TelDealComplete__c != true ){
				c.Status = '关闭';
			}
		}

	}
	//验证关闭个案
	public static void validateCloseCase(List<Case> list_new ,Map<Id,Case> oldMap ){

		Map<Id,Case> mapCase = new Map<Id,Case>();
		for (Case c : list_new ) {
			Case oldc = oldMap.get(c.Id);
			if(c.Status == '关闭' &&  oldc.Status != '关闭' && c.TelDealComplete__c != true && c.IsUpdateWorkOrder__c == oldc.IsUpdateWorkOrder__c ){
				mapCase.put(c.Id, c);
			}
		}
		if(mapCase.keySet().size() == 0) return;
		Set<String> rtSet = new Set<String>();
        rtSet.add('TeachingTraining');
        rtSet.add('Reagents');
        rtSet.add('clinicalpromotion');
        rtSet.add('InstrumentsTraining');
        rtSet.add('calibration');
        rtSet.add('MaintenanceOrder');
        rtSet.add('ProblemSolving');
        rtSet.add('InstallationOrder');
        rtSet.add('TechnicalTours');
        rtSet.add('ServiceOrder');
        rtSet.add('UsersReflect');
        rtSet.add('EvaluationTest');
        rtSet.add('SoftwareInstallationTraining');
        //查询出个案下的所有工单，检查是否都已完成
        List<WorkOrder__c> wList = [
                SELECT Id,Status__c,Case__c,Signed_Engineer__c,Case__r.RecordType.DeveloperName ,Signed_UsedDepartmen__c,ReportNumber__c,Visit__c,RecordType.DeveloperName,case__r.IsUpdateWorkOrder__c
                FROM WorkOrder__c 
                WHERE Case__c IN : mapCase.keySet()];

                Map<Id,List<WorkOrder__c>> cwMap = new Map<Id,List<WorkOrder__c>>();
                for (WorkOrder__c w : wList) {
                    List<WorkOrder__c> temp = new List<WorkOrder__c>();
                    if(cwMap.containsKey(w.Case__c)){
                        temp.addAll(cwMap.get(w.Case__c));
                    }
                    temp.add(w);
                    cwMap.put(w.Case__c, temp);
                }
                System.debug('CaseToWorkOrderHandler==>validateCloseCase');
        for (Id ck : cwMap.keySet()) {
                Boolean cando = true;
              for (WorkOrder__c w:cwMap.get(ck) ) {
                 	
                    if(		(rtSet.contains(w.RecordType.DeveloperName) && w.Status__c != '完成' )||
                    		(w.RecordType.DeveloperName != 'InstallationOrder' && 
                                 w.RecordType.DeveloperName != 'NonAgentInstallationOrder' && 
                                 w.RecordType.DeveloperName != 'ServiceOrder' && 
                                 w.RecordType.DeveloperName != 'MaintenanceOrder'
                                 &&  w.Visit__c == null)||( w.Status__c != '完成')

                             ) {

                       	mapCase.get(ck).addError('个案不能关闭!工单状态不符合条件!');
                    	break;

             		}

           		}
            
        } 


	}
/**
*1.新建/编辑 经销商个案的时候  自动生成/更新对应的工单
*2.来自微信的经销商个案的时候 自动分配所有人
*/
///分配来自微信的经销商个案 自动分配所有人 和 记录类型
	public static void matchOnwer(List<Case> list_new){
		Set<Id>  eqSet= new Set<Id>();
		for (Case c : list_new) {
			if (c.Origin == '扫码报修') {
				if(c.ServiceManufacture__c!= null)eqSet.add(c.ServiceManufacture__c);
			}
		}

		///如果是来自微信报修的个案 自动匹配个案的所有人.
		if (eqSet.size() >0) {

			//优先处理人  {仪器Id:userId }
			Map<Id,Id> userMap = new Map<Id,Id>();
			///{服务编码:[仪器Id]}
			Map<String,List<Id>> epMap = new Map<String,List<Id>>();
			///服务类型
			Map<Id,String>  epTypeMap = new Map<Id,String>();
			///服务主体编码
			Map<Id,String> responsibleCodeMap  = new Map<Id,String>();

			for (Equipment__c eq:[select Id,ServiceAccount__r.ServiceType__c,ServiceAccount__r.PriorityUser__c,
				ServiceAccount__r.ResponseCode__c from Equipment__c where Id in:eqSet]) {
					List<Id> temp = new List<Id>();
				if(eq.ServiceAccount__c != null )responsibleCodeMap.put(eq.Id, eq.ServiceAccount__r.ResponseCode__c);
				if(epMap.containsKey(eq.ServiceAccount__r.ResponseCode__c)){
					temp.addAll(epMap.get(eq.ServiceAccount__r.ResponseCode__c));
				}
				temp.add(eq.Id);
				epMap.put(eq.ServiceAccount__r.ResponseCode__c, temp);
				epTypeMap.put(eq.Id, eq.ServiceAccount__r.ServiceType__c);
				if(eq.ServiceAccount__r.PriorityUser__c != null)userMap.put(eq.Id,eq.ServiceAccount__r.PriorityUser__c);
			}


			
			///找到有效的 服务人
			/// [userid]
			Set<Id>  activeUser= new Set<Id>();
			/// {服务编码:[userid]}
			Map<String,List<Id>> resMap = new Map<String,List<Id>>();

			for (User u:[select Id,ResponseCode__c from User where isActive = true  and (ResponseCode__c in:epMap.keySet() or Id in:userMap.values())] ) {
				if (u.ResponseCode__c != null ) {
					List<Id> temp = new List<Id>();
					if(resMap.containsKey(u.ResponseCode__c)){
						temp.addAll(resMap.get(u.ResponseCode__c));
					}
					temp.add(u.Id);
					resMap.put(u.ResponseCode__c, temp);
				}
				activeUser.add(u.Id);

				
			}
			Map<Id,Id> epUserMap =new  Map<Id,Id>();
			///匹配仪器和服务人
			for (String code : epMap.keySet()) {
				
				for (Id eid : epMap.get(code)) {
					if(userMap.containsKey(eid) && activeUser.contains(userMap.get(eid))){
						epUserMap.put(eid, userMap.get(eid));
					}else{
						if(resMap.containsKey(code))epUserMap.put(eid, resMap.get(code)[0]);
					}
				}
			}
			///外部需求
			Id outRT = Utils.getRecordTypeIdByDevNameAndObjName('Service', 'Case');
			///经销商服务工单
			Id dealerRT = Utils.getRecordTypeIdByDevNameAndObjName('ServiceOrder', 'Case');
			System.debug('+++'+outRT +'===='+dealerRT);
			for (Case c : list_new) {
				if(epUserMap.get(c.ServiceManufacture__c )!= null){
					c.ResponseCode__c = responsibleCodeMap.get(c.ServiceManufacture__c); 
					c.OwnerId = epUserMap.get(c.ServiceManufacture__c);
					c.RecordTypeId = epTypeMap.get(c.ServiceManufacture__c) == '分销服务' ? dealerRT : outRT;
				}
			}
			System.debug(list_new);
		}
			System.debug('*** matchOnwer');



	} 
	///查检没有工单关闭个案
	public static void checkEngneerCloseCase(List<Case> list_new ,Map<Id,Case> oldMap){

		User u = [select Id ,Profile.Name from User where Id=:UserInfo.getUserId()];
		if(!u.Profile.Name.contains('系统管理员') ){
			Map<Id,Case>  casMap = new Map<Id,Case>();
			for (Case c :list_new ) {
				Case oldc = oldMap.get(c.Id);
				if(c.Status == '关闭' && oldc.Status != '关闭'  && c.TelDealComplete__c != true){
					casMap.put(c.Id,c);
				}
			}
			Set<Id>  casSet = new Set<Id>();
			for (WorkOrder__c w: [select Id ,Case__c  from WorkOrder__c where Case__c in: casMap.keySet()]) {
				casSet.add(w.Case__c);
			}
			for (Case c  :casMap.values() ) {
				if(!casSet.contains(c.Id)){
					c.addError('服务请求没有工单不能关闭! 若需要关闭请联系系统管理员!',false);
					break;
				}
			}

		}
		
	}
	///个案状态改变 记录状态改变的时间
	public static void caseStatusRecordTime(List<Case> list_new,Map<Id,Case> oldMap){
		for (Case c : list_new) {
			
			Case oldc = oldMap.get(c.Id);
			if(c.Status == '已升级' && oldc.Status != '已升级'  ){
				c.CaseUpgradeTime__c = System.now();
				c.IsUpdateWorkOrder__c = !c.IsUpdateWorkOrder__c;
			}else if(c.Status == '已派发' && oldc.Status != '已派发' ){
				c.CaseDispatchTime__c = System.now();
				c.IsUpdateWorkOrder__c = !c.IsUpdateWorkOrder__c;
			}else if(c.Status == '已分配' && oldc.Status != '已分配' ){
				c.CaseAssignTime__c = System.now();
				c.IsUpdateWorkOrder__c = !c.IsUpdateWorkOrder__c;

			}
			System.debug(c.Status);

		}
		System.debug('*** caseStatusRecordTime');
	}
	///非上班时间报修进来的个案 发送邮件 给你个案的所有人
	public static void  caseSendMail(List<Case> list_new){
		Set<Id>  eqSet= new Set<Id>();
		Set<Id>cset = new Set<Id>();

		for (Case c : list_new) {
			if(c.Origin == '扫码报修'){
				if(c.ServiceManufacture__c != null){
					eqSet.add(c.ServiceManufacture__c);
					cset.add(c.Id);
				}

			}
		}
		System.debug('*** caseSendMail');
		///获取发件邮箱
		Map<Id,String> mailMap = new Map<Id,String>();
		Map<Id,String> messageMap = new Map<Id,String>();
		if (cset.size() > 0) {
			for (Case c :[select Id,Account.Name ,Owner.Email from Case where Id in: cset]) {
				mailMap.put(c.Id, c.Owner.Email);
				messageMap.put(c.Id,c.Account.Name);	
			}
			
		}
		Map<Id,Id> rMap = new Map<Id,Id>();
		Set<Id> rsSet = new Set<Id>();

		for(Equipment__c eq:[select Id , ServiceAccount__c from Equipment__c where Id in: eqSet]){
			rMap.put(eq.Id, eq.ServiceAccount__c);

			if(eq.ServiceAccount__c != null )rsSet.add(eq.ServiceAccount__c);
		} 
		Map<Id,Boolean> sendMap = new Map<Id,Boolean>();
		for (ResponsibleServer__c rs : [select Id,WorkOnTime__c,WorkOffTime__c,VacationStartDate__c,VacationEndDate__c,
			VacationWorkStartDate__c,VacationWorkEndDate__c from ResponsibleServer__c where Id in:rsSet ]) {
			sendMap.put(rs.Id, isSendMail(rs));
		}

		Messaging.SingleEmailMessage[] mList = new Messaging.SingleEmailMessage[]{};
		for ( Case c : list_new ) {
			if(sendMap.containsKey(rMap.get(c.ServiceManufacture__c)) && sendMap.get(rMap.get(c.ServiceManufacture__c)) == true ){

				Messaging.reserveSingleEmailCapacity(1);
				
				Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
				String[] toAddresses = new String[] {mailMap.get(c.Id)};
				mail.setToAddresses(toAddresses);
				//mail.setReplyTo('support@acme.com');
				mail.setSenderDisplayName('Salesforce Support');
				mail.setSubject('微信报修服务请求' );
				mail.setBccSender(false);
				mail.setUseSignature(false);
				mail.setPlainTextBody(messageMap.get(c.Id)+'通过微信发起了报修请求!');
				mail.setHtmlBody('<a href=https://ap7.salesforce.com/'+c.Id+'>点击查看详情!</a>');
				if(!mailMap.containsKey(c.Id))continue;
				mList.add(mail);
			}

		}
		 if(mList.size() > 0 )Messaging.sendEmail(mList);


	}
 	


	public static void changeWorkOrderRecordType(){




	}
	///生成工单
	public static void genWorkOrder(List<Case> list_new,Map<Id,Case> oldMap,Boolean isInsert,Boolean isUpdate  ){

		System.debug('*** genWorkOrder');
		
		Set<String> rtSet = new Set<String>();
		rtSet.add('TeachingTraining');
		rtSet.add('Reagents');
		rtSet.add('clinicalpromotion');
		rtSet.add('InstrumentsTraining');
		rtSet.add('calibration');
		rtSet.add('MaintenanceOrder');
		rtSet.add('ProblemSolving');
		rtSet.add('InstallationOrder');

		rtSet.add('TechnicalTours');
		rtSet.add('ServiceOrder');
		rtSet.add('UsersReflect');
		rtSet.add('EvaluationTest');
		rtSet.add('SoftwareInstallationTraining');
		rtSet.add('Relocation');
		rtSet.add('CalibrationEngineer');
		rtSet.add('Upgrade');
		Map<Id,String> rtIDMap = new Map<Id,String> ();
		Map<String,Id> woRTMap = new Map<String,Id>();
		//for(RecordType r :[select Id,DeveloperName from RecordType where SobjectType = 'Case' and DeveloperName in:rtSet]){
			//rtIDMap.put(r.Id,r.DeveloperName);
		//}

		for(RecordType r :[select Id,DeveloperName from RecordType where SobjectType = 'WorkOrder__c' ]){
			woRTMap.put(r.DeveloperName,r.Id);
		}



		/*
		List<WorkO		for(Case c : list_new){
rder__c> woList = new List<WorkOrder__c>();
			if(rtIDMap.keySet().contains(c.RecordTypeId)){
				WorkOrder__c wo = gen(c,true);
				wo.RecordTypeId = woRTMap.get(rtIDMap.get(c.RecordTypeId));
 				woList.add(wo);
			}
		}
	
		if(woList.size() > 0)insert woList;
		*/
		


		Map<Id,Case>cMap= new Map<Id,Case>();
		for (Case c : list_new) {
				
			cMap.put(c.Id ,c);

		}
		List<WorkOrder__c> woList = new List<WorkOrder__c>();
		Set<Id> oldEngineers = new Set<Id>(); 
		Map<Id,Id> casEngineerMap = new Map<Id,Id>();//个案:新工程师 Map
		Set<Id> casSetU = new Set<Id>();
		for(Case c :[select Id,ServicePlan__r.Servicetype__c, User__c ,Engineer__c,Engineer__r.Profile.Name,Engineer__r.EngineeringAssistant__c ,Subject ,RecordType.DeveloperName ,TechnicalServicesApplicationNum__c,
			InstallationApply__c,Return_Machine__c,InstrumentScrapping__c,OwnerId , TechnicalServicesApplicationNum__r.Owner.Profile.Name,
			TechnicalServicesApplicationNum__r.RecordType.DeveloperName,TechnicalServicesApplicationNum__r.Type__c ,
			(select Id from WorkOrder__r ) 
			 from Case where Id in: cMap.keyset()]){

			Case old = oldMap == null ? new Case() : oldMap.get(c.Id );
			Case newCase = cMap.get(c.Id);

			if(isInsert){//如果是新建 
				//新建个案的时候: 要自动生成工单的情况: 1.个案-->技术服务申请--->记录类型:工程服务请求 
				//	                             2.个案-->创建人:经销商(或: 记录类型为经销商个案)


				//2020 -07-16

				/*
					技术服务申请(主题)>>>>工单(记录类型)

					当技术服务申请的记录类型为 EngineeringServiceRequest、DealerSupportApplication时，技术服务申请的主题与工单类型的对应关系：
					产品问题维修、C800启用ISE>>>>ServiceOrder
					保养>>>>MaintenanceOrder
					仪器校准>>>>CalibrationEngineer
					仪器升级>>>>Upgrade
					移机>>>>Relocation
					当技术服务申请的记录类型为 EngineeringServiceRequest时，技术服务申请的主题与工单类型的对应关系：
					EngineeringEmergencyInstallation时，技术服务申请的主题与工单类型的对应关系：
					安装>>>>InstallationOrder

				*/

				if(rtSet.contains(c.RecordType.DeveloperName) || c.TechnicalServicesApplicationNum__r.RecordType.DeveloperName == 'EngineeringServiceRequest' || c.ServicePlan__r.Servicetype__c == '工程' || c.TechnicalServicesApplicationNum__r.RecordType.DeveloperName == 'EngineeringEmergencyInstallation'  ){


					WorkOrder__c wo = gen(newCase,true);//MaintenanceOrder保养 ServiceOrder产品问题维修
					wo.Status__c = '生单';

					if(rtSet.contains(c.RecordType.DeveloperName) && c.RecordType.DeveloperName != 'InstallationOrder')wo.FullIn_Completed__c = true;

					if(c.ServicePlan__r.Servicetype__c == '工程'  ){
						wo.RecordTypeId =  woRTMap.get('MaintenanceOrder');

					}else if( c.TechnicalServicesApplicationNum__r.RecordType.DeveloperName == 'EngineeringServiceRequest' || c.ServicePlan__c != null  ){
						//技术服务申请

						
						if(!c.TechnicalServicesApplicationNum__r.Owner.Profile.Name.contains('工程'))continue;

						if(c.TechnicalServicesApplicationNum__r.Type__c == '保养' )wo.RecordTypeId =  woRTMap.get('MaintenanceOrder');
						if(c.TechnicalServicesApplicationNum__r.Type__c == '产品问题维修' )wo.RecordTypeId =  woRTMap.get('ServiceOrder');
						if(c.TechnicalServicesApplicationNum__r.Type__c == 'C800启用ISE' )wo.RecordTypeId =  woRTMap.get('ServiceOrder');
						if(c.TechnicalServicesApplicationNum__r.Type__c == '仪器校准' )wo.RecordTypeId =  woRTMap.get('CalibrationEngineer');
						if(c.TechnicalServicesApplicationNum__r.Type__c == '仪器升级' )wo.RecordTypeId =  woRTMap.get('Upgrade');
						if(c.TechnicalServicesApplicationNum__r.Type__c == '移机' )wo.RecordTypeId =  woRTMap.get('Relocation');

						if(wo.RecordTypeId == null ) continue;//都 不是就过

					}else if( c.TechnicalServicesApplicationNum__r.RecordType.DeveloperName == 'EngineeringEmergencyInstallation'){

						if(c.TechnicalServicesApplicationNum__r.Type__c == '安装')wo.RecordTypeId = c.Engineer__r.EngineeringAssistant__c ? woRTMap.get('NonAgentInstallationOrder') : woRTMap.get('InstallationOrder');

						if(wo.RecordTypeId == null ) continue;//都 不是就过

					}else{
						wo.RecordTypeId =  woRTMap.get(c.RecordType.DeveloperName);
					}
	 				woList.add(wo);
				}
			}

			if(isUpdate){

				//在个案更新的时候且分配工程师: 
				//1.个案-->技术服务申请--->记录类型:经销商支援 
				//2.个案-->退换机申请--->
				if( c.WorkOrder__r.size() == 0 && (c.InstallationApply__c != null || c.Return_Machine__c != null ||c.InstrumentScrapping__c != null || 
					 (c.TechnicalServicesApplicationNum__c != null && (c.TechnicalServicesApplicationNum__r.RecordType.DeveloperName == 'EngineeringServiceRequest' || 
					 	c.TechnicalServicesApplicationNum__r.RecordType.DeveloperName == 'DealerSupportApplication' || c.TechnicalServicesApplicationNum__r.RecordType.DeveloperName == 'SupportApplicationLocked')) ) 
					&& newCase.Engineer__c != old.Engineer__c && newCase.Engineer__c != null ){
					//新建工单
					System.debug('genWorkOrder==>'+newCase );
					WorkOrder__c wo = gen(newCase,true);//MaintenanceOrder保养 ServiceOrder产品问题维修
					wo.Status__c = '生单';

					if(  c.TechnicalServicesApplicationNum__r.RecordType.DeveloperName == 'EngineeringServiceRequest' || c.TechnicalServicesApplicationNum__r.RecordType.DeveloperName == 'DealerSupportApplication' || c.TechnicalServicesApplicationNum__r.RecordType.DeveloperName == 'SupportApplicationLocked'){
						

						if(c.TechnicalServicesApplicationNum__r.Type__c == '保养' )wo.RecordTypeId =  woRTMap.get('MaintenanceOrder');
						if(c.TechnicalServicesApplicationNum__r.Type__c == '产品问题维修' )wo.RecordTypeId =  woRTMap.get('ServiceOrder');
						if(c.TechnicalServicesApplicationNum__r.Type__c == 'C800启用ISE' )wo.RecordTypeId =  woRTMap.get('ServiceOrder');
						// if(c.TechnicalServicesApplicationNum__r.Type__c == '安装' )wo.RecordTypeId =  woRTMap.get('InstallationOrder');
						if(c.TechnicalServicesApplicationNum__r.Type__c == '仪器校准' )wo.RecordTypeId =  woRTMap.get('CalibrationEngineer');
						if(c.TechnicalServicesApplicationNum__r.Type__c == '仪器升级' )wo.RecordTypeId =  woRTMap.get('Upgrade');
						if(c.TechnicalServicesApplicationNum__r.Type__c == '移机' )wo.RecordTypeId =  woRTMap.get('Relocation');


						if(wo.RecordTypeId == null ) continue;//都不是 就过
					}else if(c.InstallationApply__c != null){
						//如果 是 工程助理
						wo.RecordTypeId = c.Engineer__r.EngineeringAssistant__c ? woRTMap.get('NonAgentInstallationOrder') : woRTMap.get('InstallationOrder');
						if(c.Engineer__r.EngineeringAssistant__c || c.Engineer__r.Profile.Name.contains('经销商'))  wo.Status__c = '处理中';

					}else if(c.Return_Machine__c != null || c.InstrumentScrapping__c != null ){
						//2020年5.27 从保养工单改为服务工单 
						//2020.08.13 改为移机工单
						wo.RecordTypeId =  woRTMap.get('Relocation');

					}else{

						wo.RecordTypeId =  woRTMap.get(c.RecordType.DeveloperName);

					}
	 				woList.add(wo);

				}

				System.debug('genWorkOrder==>'+c.WorkOrder__r.size());
				if( c.WorkOrder__r.size() == 1 &&  (c.InstallationApply__c != null || c.Return_Machine__c != null || c.TechnicalServicesApplicationNum__c != null ||  c.ServicePlan__r.Servicetype__c == '工程' ) 

					&& old.Engineer__c != newCase.Engineer__c  && newCase.Engineer__c != null  ){
					//如果是技术服务申请,退换机申请, 安装申请的服务请求 
					//工程师变化 去修改工单的技术人员 
					//修改原来工程师的权限 
					if(c.OwnerId != old.Engineer__c )oldEngineers.add(old.Engineer__c);
					casEngineerMap.put(c.Id , c.Engineer__c);
				}


			}

			if(old.User__c != null && old.User__c != newCase.User__c && old.User__c != c.OwnerId ){
				oldEngineers.add(old.User__c);
				casSetU.add(c.Id);
			}



		}
			casSetU.addAll(casEngineerMap.keySet());
				System.debug('genWorkOrder==>woList'+woList);
					if(woList.size() > 0 ) insert woList;
				System.debug('genWorkOrder==>casEngineerMap'+casEngineerMap);

		//工程师变化 去修改工单的技术人员 
		//修改原来工程师的权限 
		if(casEngineerMap.keySet().size() > 0){
			Map<Id,WorkOrder__c> woMap = new Map<Id,WorkOrder__c>();//只更新个案下的一个工单的技术人员
			for( WorkOrder__c wo : [select Id,Technician__c,Case__c from WorkOrder__c where Case__c in: casEngineerMap.keySet() ]){
				
				if(casEngineerMap.containsKey(wo.Case__c)){

					wo.Technician__c = casEngineerMap.get(wo.Case__c);

					woMap.put(wo.Case__c, wo);
				}

			}


         	
         	if(woMap.values().size() > 0) update  woMap.values();
		}
		List<Caseshare> csList = [select Id, CaseAccessLevel, RowCause from Caseshare where CaseId in: casSetU and UserOrGroupId in: oldEngineers ];
         	if(csList.size() > 0) delete csList;
		 	
		
	}
	///安装服务请求分配给经销商 则修改服务请求的记录类型位经销商安装服务请求
	//2020-07-28服务请求的记录类型为Installation的，当工程师变更为用户上为工程助理的用户时，工单记录类型变更为 非代理工单
	public static void changeInstallCaseRecordType(List<Case> list_new ,Map<Id,Case>oldMap){
		
		Map<Id,Id>  newEngine= new Map<Id,Id>();
		Set<Id> userSet = new Set <Id>();
		for (Case c : list_new) {
			Case old = oldMap.get(c.Id);
			System.debug('***'+c.Engineer__c +'-->'+old.Engineer__c);
			
			if(c.Engineer__c != null && old.Engineer__c != c.Engineer__c  ){
				
				if(c.Engineer__c != null )newEngine.put(c.Id,c.Engineer__c);
				if(c.Engineer__c != null )userSet.add(c.Engineer__c);
			}


		}
		System.debug('*** changeInstallCaseRecordType');
		if(userSet.size() == 0)return;
		Map<Id,User> uMap = new Map<Id,User>();

		for(User u : [select Id ,Profile.Name,EngineeringAssistant__c from User where Id in:userSet]){
			
			uMap.put(u.Id,u);

		}
		System.debug('***'+uMap +'-->'+ userSet);
		Id installRT = Utils.getRecordTypeIdByDevNameAndObjName('Installation', 'Case');

		Id installOrderRT = Utils.getRecordTypeIdByDevNameAndObjName('InstallationOrder', 'Case');
		
		System.debug('***'+installOrderRT +'-'+installRT );

		Map<Id,Id> csMap = new Map<Id,Id>();
		for (Case c :  list_new) {
			
			System.debug(c.Status);

			if(c.RecordTypeId == installOrderRT || c.RecordTypeId == installRT){
				
				User u = uMap.get(newEngine.get(c.Id));
				
				System.debug('***'+ u);

				if(u.Profile.name == '迈克经销商' && c.RecordTypeId != installOrderRT){

					c.RecordTypeId = installOrderRT;

				}else if((u.Profile.name != '迈克经销商' && c.RecordTypeId != installRT)){

					c.RecordTypeId = installRT;

				}

				if(u.EngineeringAssistant__c && c.RecordTypeId == installRT )csMap.put(c.Id,u.Id  );
			}			

		}
		if(csMap.isEmpty())return;

		Id woInstallRtype = Utils.getRecordTypeIdByDevNameAndObjName('NonAgentInstallationOrder', 'WorkOrder__c');
		List<WorkOrder__c> woL = new List<WorkOrder__c>();
		for (WorkOrder__c wo  :[select Id ,RecordTypeId,Case__c  from WorkOrder__c where Case__c in: csMap.keySet()] ) {
			if(wo.RecordTypeId !=woInstallRtype ){
				wo.RecordTypeId = woInstallRtype;
				wo.Technician__c = csMap.get(wo.Case__c);
				woL.add(wo);
			}
		}

		if(!woL.isEmpty())update woL;




	}
	///安装服务请求分配给经销商用户 自动生成安装工单
	public static void genInstallWorkOrder(Map<Id,Case> newMap ,Map<Id,Case> oldMap){
		/*Set<Id> cset = new Set<Id> ();
		Set<Id> deleteset = new Set<Id>();
		Set<Id> deleteEnginer = new Set<Id>();
		for (Case c : newMap.values()) {
			Case old = oldMap.get(c.Id);
			if(c.Engineer__c != null && old.Engineer__c != c.Engineer__c){
				cset.add(c.Id);

				if(old.Engineer__c != null){
					deleteset.add(c.Id);
					deleteEnginer.add(old.Engineer__c);
				}
			}


		}
		///如果 是修改工程师  如果原有的工程师 是经销商则要删除自动生成的工单
		System.debug('***'+deleteset+'-->' +deleteEnginer);

		if(deleteset.size() > 0){
			List<WorkOrder__c> deleList = new List<WorkOrder__c>();
			for (WorkOrder__c wo : [select Id,Case__c,Technician__c,Technician__r.Profile.Name ,Case__r.RecordType.DeveloperName  from WorkOrder__c where Case__c in:deleteset and Technician__c in:deleteEnginer and Status__c != '完成']) {
			System.debug('***'+wo);
				if(wo.Case__r.RecordType.DeveloperName == 'Installation' && wo.Technician__r.Profile.Name  == '迈克经销商'){
					deleList.add(wo);
				}
			}
			if(deleList.size() >0) delete deleList;
		}


		if(cset.size() == 0)return;
		Map<Id,Case> casMap = new Map<Id,Case>();
		Map<Id,Id> engineer = new Map<Id,Id>();

		for(Case c :[select Id,RecordType.DeveloperName ,Engineer__c ,Engineer__r.Profile.Name from Case where Id in:cset]){
			if(c.RecordType.DeveloperName == 'InstallationOrder' &&
				c.Engineer__r.Profile.Name == '迈克经销商'){
				//|| c.RecordType.DeveloperName == 'NonAgentInstallationOrder'
				casMap.put(c.Id,newMap.get(c.Id));
				engineer.put(c.Id,c.Engineer__c);
			}
		}
		System.debug('***'+casMap+'-->' +engineer);
		if(casMap.keySet().size() == 0)return;
		for (WorkOrder__c wo : [select Id,Case__c,Technician__c,Technician__r.Profile.Name  from WorkOrder__c where Case__c in:casMap.keySet() and Technician__c in:engineer.values()]) {
			if(casMap.containsKey(wo.Case__c)){
				casMap.remove(wo.Case__c);
			}
		}
		System.debug('***'+casMap);

		if(casMap.keySet().size() == 0 )return;
		List<WorkOrder__c> woList = new List<WorkOrder__c>();
		Id rtid = Utils.getRecordTypeIdByDevNameAndObjName('InstallationOrder', 'WorkOrder__c');
		for (Case c : casMap.values()) {
			
			WorkOrder__c wo = gen(c, true);
			wo.RecordTypeId = rtid;
			wo.Technician__c = c.Engineer__c;
			//wo.ServiceEngineerName__c = c.
			System.debug('***' + wo);
			woList.add(wo);

		}
		System.debug('*** genInstallWorkOrder');
		if(woList.size() > 0) insert woList;
		*/


	}
	////更新工单
	//服务请求的记录类型为Installation的，当工程师变更为用户上为工程助理的用户时，工单记录类型变更为 非代理工单
	public static void updateWorkOrder(List<Case> list_new,Map<Id,Case> oldMap ){

		Set<String> rtSet = new Set<String>();
		rtSet.add('TeachingTraining');
		rtSet.add('Reagents');
		rtSet.add('clinicalpromotion');
		rtSet.add('InstrumentsTraining');
		rtSet.add('calibration');
		rtSet.add('MaintenanceOrder');
		rtSet.add('ProblemSolving');
		rtSet.add('InstallationOrder');
		rtSet.add('TechnicalTours');

		rtSet.add('ServiceOrder');
		rtSet.add('UsersReflect');
		rtSet.add('EvaluationTest');
		rtSet.add('SoftwareInstallationTraining');
		rtSet.add('Relocation');
		rtSet.add('CalibrationEngineer');
		rtSet.add('Upgrade');
		Map<Id,String> rtIDMap = new Map<Id,String> ();
		Map<String,Id> woRTMap = new Map<String,Id>();
		for(RecordType r :[select Id,DeveloperName from RecordType where SobjectType = 'Case' and DeveloperName in:rtSet]){
			rtIDMap.put(r.Id,r.DeveloperName);
		}
		Map<Id,Case>casMap = new Map<Id,Case>();
		for (Case c  : list_new) {
			Case oldc = oldMap.get(c.Id);

			System.debug('***'+c.IsUpdateWorkOrder__c + '-->'+oldc.IsUpdateWorkOrder__c);

			if(c.Status != '关闭' && rtIDMap.containsKey(c.RecordTypeId) && c.IsUpdateWorkOrder__c == oldc.IsUpdateWorkOrder__c )casMap.put(c.Id,c);	
			System.debug(c.Status);

		}
		System.debug('*** updateWorkOrder');
		if(casMap.keySet().size()  == 0)return;
		List<WorkOrder__c> woList = new List<WorkOrder__c>();
		for (WorkOrder__c wo: [select Id ,Case__c from WorkOrder__c where Case__c in:casMap.keySet() and Status__c != '完成']) {
			if(casMap.containsKey(wo.Case__c)){
				WorkOrder__c newwo = gen(casMap.get(wo.Case__c),false);

				newwo.Id = wo.Id;
				woList.add(newwo);
			}

		}
		System.debug(woList);
		if(woList.size() > 0)update woList;

	}

	public static void forbidUpdate (List<Case> list_new ,Map<Id,Case> oldMap){
		List<Case> cList = new List<Case>();
		for (Case c: list_new) {
			Case oldc = oldMap.get(c.Id);
			System.debug('**-->'+c.IsUpdateWorkOrder__c +'-->'+oldc.IsUpdateWorkOrder__c);

			if( oldc.Status == '关闭'  && c.Status !=oldc.Status  && c.IsUpdateWorkOrder__c == oldc.IsUpdateWorkOrder__c && c.InstallationApply__c == oldc.InstallationApply__c ){
				cList.add(c);
			}
		}
		System.debug('*** forbidUpdate');
		if(cList.size()== 0 ) return;
		User u = [select Id, Profile.Name from User where  Id =:UserInfo.getUserId()];
		System.debug(cList);
		if(cList.size() > 0 && u.Profile.Name != '系统管理员'){
			for (Case c: cList) {
				System.debug('<--->');
				c.addError('服务请求已经关闭,不能修改!请联系系统管理员!',false);
			}
		}
	

	}
	public static WorkOrder__c gen(Case c,Boolean isInsert ){

		WorkOrder__c wo = new WorkOrder__c();
		if(c.LineType__c != null )wo.LineType__c = c.LineType__c;
		//AssociatedEquipment__c
		if(c.LineInstrument__c != null )wo.LineInstrument__c = c.LineInstrument__c;
		if(c.InstrumentCloud__c != null )wo.InstrumentCloud__c = c.InstrumentCloud__c;
		if(c.CardNO__c != null )wo.CardNO__c = c.CardNO__c;
		if(c.Ship_No__c != null )wo.Ship_No__c = c.Ship_No__c;
		if(c.ISE__c != null )wo.ISE__c = c.ISE__c;

		if(c.Install_End_Datetime__c != null)wo.Install_End_Datetime__c = c.Install_End_Datetime__c;
		//LineType__c
		//CombinationForm__c
		
		
		 


		if(c.ActualSituation1__c != null )wo.ActualSituation1__c = c.ActualSituation1__c;
		if(c.IsMeetRequirement1__c != null )wo.IsMeetRequirement1__c = c.IsMeetRequirement1__c;
		if(c.NormalRequirement1__c != null )wo.NormalRequirement1__c = c.NormalRequirement1__c;
		if(c.ActualSituation10__c != null )wo.ActualSituation10__c = c.ActualSituation10__c;

		if(c.IsMeetRequirement10__c != null )wo.IsMeetRequirement10__c = c.IsMeetRequirement10__c;
		if(c.NormalRequirement10__c != null )wo.NormalRequirement10__c = c.NormalRequirement10__c;
		if(c.ActualSituation11__c != null )wo.ActualSituation11__c = c.ActualSituation11__c;

		if(c.IsMeetRequirement11__c != null )wo.IsMeetRequirement11__c = c.IsMeetRequirement11__c;
		if(c.NormalRequirement11__c != null )wo.NormalRequirement11__c = c.NormalRequirement11__c;


		if(c.ActualSituation2__c != null )wo.ActualSituation2__c = c.ActualSituation2__c;
		if(c.IsMeetRequirement2__c != null )wo.IsMeetRequirement2__c = c.IsMeetRequirement2__c;
		if(c.NormalRequirement2__c != null )wo.NormalRequirement2__c = c.NormalRequirement2__c;

		if(c.ActualSituation3__c != null )wo.ActualSituation3__c = c.ActualSituation3__c;
		if(c.IsMeetRequirement3__c != null )wo.IsMeetRequirement3__c = c.IsMeetRequirement3__c;
		if(c.NormalRequirement3__c != null )wo.NormalRequirement3__c = c.NormalRequirement3__c;

		if(c.ActualSituation4__c != null )wo.ActualSituation4__c = c.ActualSituation4__c;
		if(c.IsMeetRequirement4__c != null )wo.IsMeetRequirement4__c = c.IsMeetRequirement4__c;
		if(c.NormalRequirement4__c != null )wo.NormalRequirement4__c = c.NormalRequirement4__c;

		if(c.ActualSituation5__c != null )wo.ActualSituation5__c = c.ActualSituation5__c;
		if(c.IsMeetRequirement5__c != null )wo.IsMeetRequirement5__c = c.IsMeetRequirement5__c;
		if(c.NormalRequirement5__c != null )wo.NormalRequirement5__c = c.NormalRequirement5__c;

		if(c.ActualSituation6__c != null )wo.ActualSituation6__c = c.ActualSituation6__c;
		if(c.IsMeetRequirement6__c != null )wo.IsMeetRequirement6__c = c.IsMeetRequirement6__c;
		if(c.NormalRequirement6__c != null )wo.NormalRequirement6__c = c.NormalRequirement6__c;

		if(c.ActualSituation7__c != null )wo.ActualSituation7__c = c.ActualSituation7__c;
		if(c.IsMeetRequirement7__c != null )wo.IsMeetRequirement7__c = c.IsMeetRequirement7__c;
		if(c.NormalRequirement7__c != null )wo.NormalRequirement7__c = c.NormalRequirement7__c;

		if(c.ActualSituation8__c != null )wo.ActualSituation8__c = c.ActualSituation8__c;
		if(c.IsMeetRequirement8__c != null )wo.IsMeetRequirement8__c = c.IsMeetRequirement8__c;
		if(c.NormalRequirement8__c != null )wo.NormalRequirement8__c = c.NormalRequirement8__c;
		if(c.ActualSituation9__c != null )wo.ActualSituation9__c = c.ActualSituation9__c;
		if(c.IsMeetRequirement9__c != null )wo.IsMeetRequirement9__c = c.IsMeetRequirement9__c;
		if(c.NormalRequirement9__c != null )wo.NormalRequirement9__c = c.NormalRequirement9__c;

		wo.Kit__c = c.Kit__c;
		
		if(c.OpponentStatus__c != null) wo.OpponentStatus__c = c.OpponentStatus__c;
		if(c.NextPlan__c != null )wo.NextPlan__c = c.NextPlan__c;
		if(c.Id != null )wo.Case__c = c.Id;
		if(c.ProductType__c != null )wo.ProductType__c = c.ProductType__c;
		if(c.InstallationDebugging__c != null )wo.InstallationDebugging__c = c.InstallationDebugging__c;
		if(c.InstrumentUsed__c != null )wo.InstrumentUsed__c = c.InstrumentUsed__c;
		if(c.Software_Version__c != null )wo.Software_Version__c = c.Software_Version__c;
		if(c.OperationCategory__c != null )wo.OperationCategory__c = c.OperationCategory__c;
		//wo.Signed_UsedDepartmen__c = c.Signed_UsedDepartmen__c;
		//if(c.Faultlevel2__c != null  )wo.Faultlevel2__c
		if(c.UserContact__c  != null )wo.UserDepartmentContact__c = c.UserContact__c;
		if(c.WarrantyStatus__c  != null )wo.WarrantyStatus__c = c.WarrantyStatus__c;
		if(c.Maintenance_Content__c  != null )wo.Maintenance_Content__c = c.Maintenance_Content__c;
		if(c.MaintenanceItems__c  != null )wo.MaintenanceItems__c = c.MaintenanceItems__c;
		if(c.AssociatedEquipment__c  != null )wo.AssociatedEquipment__c = c.AssociatedEquipment__c;
		if(c.AgainReason__c  != null )wo.AgainReason__c = c.AgainReason__c;
		if(c.StartOffAddress__c  != null )wo.StartOffAddress__c = c.StartOffAddress__c;
		//wo.StartOffCoordinates__c = c.StartOffCoordinates__c;
		//wo.ArriveCoordinates__c = c.ArriveCoordinates__c;
		if(c.NumberofPersons__c != null )wo.NumberofPersons__c =c.NumberofPersons__c;
		if(c.TrainContent__c != null )wo.TrainContent__c = c.TrainContent__c;
		if(c.TrainGoal__c != null )wo.TrainGoal__c = c.TrainGoal__c;
		if(c.TrainResult__c != null )wo.TrainResult__c = c.TrainResult__c;
		if(c.TrainingGroup__c != null )wo.TrainingGroup__c = c.TrainingGroup__c;
		if(c.TrainingType__c != null )wo.TrainingType__c = c.TrainingType__c;
		//wo.FullIn_Completed__c = c.FullIn_Completed__c;
		if(c.ProcessResult__c != null )wo.ProcessResult__c = c.ProcessResult__c;
		if(c.note__c != null )wo.note__c = c.note__c;
		if(c.Manufacturer__c != null )wo.ManufactureInfo__c = c.Manufacturer__c;
		if(c.InstallationNumber__c != null )wo.InstallationNumber__c = c.InstallationNumber__c;
		if(c.InstallationApply__c != null )wo.WorkOrderInstallApplication__c = c.InstallationApply__c;
		if(c.DepartureTime__c != null )wo.DepartureTime__c = c.DepartureTime__c;
		//wo.Signed_Engineer__c = c.Signed_Engineer__c;
		if(c.Reason_Desc__c != null )wo.Reason_Desc__c = c.Reason_Desc__c;
		if(c.Tech_Handle__c != null )wo.Tech_Handle__c = c.Tech_Handle__c;
		if(c.Software__c != null )wo.Software__c = c.Software__c;
		if(c.Software_Name__c != null )wo.Software_Name__c = c.Software_Name__c;
		if(c.Reporter_Version__c != null )wo.Reporter_Version__c = c.Reporter_Version__c;
		if(c.ArriveAddress__c != null )wo.ArriveAddress__c = c.ArriveAddress__c;
		if(c.VisitGoal__c != null )wo.VisitGoal__c = c.VisitGoal__c;
		if(c.VisitDepartment__c != null )wo.VisitDepartment__c = c.VisitDepartment__c;
		if(c.IsTeachingTraining__c != null )wo.IsTeachingTraining__c = c.IsTeachingTraining__c;
		if(c.Teachingtime__c != null )wo.Teachingtime__c = c.Teachingtime__c;
		if(c.FaultTypes__c != null )wo.FaultTypes__c = c.FaultTypes__c;
		if(c.FaultDeals__c != null )wo.FaultDeals__c = c.FaultDeals__c;
		if(c.ServiceInstrumentCP__c!= null  )wo.ServiceInstrumentCP__c = c.ServiceInstrumentCP__c;
		 if(c.Faultcode__c  != null )wo.Faultcode__c = c.Faultcode__c;
		 if(c.Failuretime__c  != null )wo.Failuretime__c = c.Failuretime__c;
		 if(c.Faultlevel2__c  != null )wo.Faultlevel2__c = c.Faultlevel2__c;
		 if(c.Faultlevel3__c  != null )wo.Faultlevel3__c = c.Faultlevel3__c;
		 if(c.lis__c != null )wo.lis__c = c.lis__c;
		 if(c.BloodCollectionTubeInformation__c != null) wo.BloodCollectionTubeInformation__c = c.BloodCollectionTubeInformation__c;
		 if(c.Participant__c  != null )wo.Participant__c = c.Participant__c;

		if(c.Fault_Freq__c != null )wo.Fault_Freq__c = c.Fault_Freq__c;
		if(c.DataAnalysis__c != null )wo.DataAnalysis__c = c.DataAnalysis__c;
		if(c.PDFReport__c != null )wo.PDFReport__c = c.PDFReport__c;
		if(c.ServiceTracking__c != null )wo.ServiceTracking__c = c.ServiceTracking__c;
		if(c.ReagentInformation__c != null ) wo.ReagentInformation__c = c.ReagentInformation__c;
		if(c.ChangeNo__c != null ) wo.ChangeNo__c = c.ChangeNo__c;
		wo.WhetherToMakeASingle__c = c.WhetherToMakeASingle__c == null ? '否' : c.WhetherToMakeASingle__c ;

		if(c.ServiceManufacture__c != null )wo.ServiceManufacture__c = c.ServiceManufacture__c;
		///wo.Install_End_Datetime__c = c.Install_End_Datetime__c;
		if(c.ServiceEngineerName__c != null )wo.ServiceEngineerName__c = c.ServiceEngineerName__c;
		if(c.Install_Start_Datetime__c != null )wo.Install_Start_Datetime__c = c.Install_Start_Datetime__c;
		if(c.ServiceSituation__c != null )wo.ServiceSituation__c = c.ServiceSituation__c;
		if(c.ServiceMethod__c != null )wo.ServiceMethod__c = c.ServiceMethod__c;
		if(c.ServiceTrackingNotes__c != null )wo.ServiceTrackingNotes__c = c.ServiceTrackingNotes__c;
		if(c.ServicesTrackingTime__c != null )wo.ServicesTrackingTime__c = c.ServicesTrackingTime__c;
		if(c.IMEINumber__c != null )wo.IMEINumber__c = c.IMEINumber__c;
		if(c.Maintenance_Info__c != null )wo.Maintenance_Info__c = c.Maintenance_Info__c;
		if(c.TestPerDay__c != null )wo.TestPerDay__c = c.TestPerDay__c;
		if(c.GenerateTechnicalServiceReportTime__c != null )wo.GenerateTechnicalServiceReportTime__c = c.GenerateTechnicalServiceReportTime__c;
		if(c.ManagementContact__c != null )wo.ManagementDepContact__c = c.ManagementContact__c;
		//if(c.CombinationForm_Ins__c != null )wo.CombinationForm_Ins__c = c.CombinationForm_Ins__c;
		if(c.CombinationForm__c != null )wo.CombinationForm__c = c.CombinationForm__c;

		if(c.ResultsSuggestions__c != null )wo.ResultsSuggestions__c = c.ResultsSuggestions__c;
		if(c.ContactId != null )wo.Contact__c = c.ContactId;
		if(c.ExperimentalPurposes__c != null )wo.ExperimentalPurposes__c = c.ExperimentalPurposes__c;
		if(c.ReagentConsumables__c != null )wo.ReagentConsumables__c = c.ReagentConsumables__c;
		if(c.Instruction__c != null )wo.Instruction__c = c.Instruction__c;
		if(c.OutTime__c != null )wo.OutTime__c = c.OutTime__c;
		if(c.AccountId != null )wo.Account__c = c.AccountId;
		//wo.CurrentLocation__c = c.CurrentLocation__c;
		if(c.InstrumentVersion__c != null )wo.InstrumentVersion__c = c.InstrumentVersion__c;
		if(c.IS_1200FaultyComponent__c != null )wo.IS_1200FaultyComponent__c = c.IS_1200FaultyComponent__c;
		if(c.Terminal__c != null )wo.Terminal__c = c.Terminal__c;
		if(c.WorkOrderStatus__c  != null )wo.Status__c = c.WorkOrderStatus__c;
		if(isInsert == true) wo.Status__c = '处理中';
		wo.Technician__c = c.Engineer__c !=null ? c.Engineer__c :c.OwnerId;
		if(c.InstallData__c != null )wo.InstallData__c = c.InstallData__c ; 
		System.debug('*** gen');
		return wo ;
	}

	public static Boolean isSendMail(ResponsibleServer__c rs){
		///现在的时间
		DateTime nw = System.now().addHours(8);
		System.debug('*** isSendMail');

		///在工作时间内
		if(nw.hour() <= rs.WorkOffTime__c.hour() && 
			nw.hour() >= rs.WorkOnTime__c.hour() &&
			 nw.minute() >  rs.WorkOnTime__c.minute() &&
			nw.minute() < rs.WorkOffTime__c.minute()  ){
			///判断是不是周末
			if(Date.valueOf(nw).toStartOfWeek().daysBetween(Date.valueOf(nw))>4){///周末
				///判断周末上不上班
				if(rs.VacationWorkStartDate__c != null && rs.VacationWorkEndDate__c != null  ){//如果周末上班

					if(rs.VacationWorkStartDate__c.year() <=nw.year() &&
					rs.VacationWorkStartDate__c.month() <= nw.month() && 
					rs.VacationWorkStartDate__c.day() <= nw.day() &&
					rs.VacationWorkEndDate__c.year() >=nw.year() &&
					rs.VacationWorkEndDate__c.month() >= nw.month() && 
					rs.VacationWorkEndDate__c.day() >= nw.day() )return false;
				}


				return true;
			}else{ ///判断平时 上不上班
				if(rs.VacationStartDate__c != null && rs.VacationEndDate__c!= null ){//如果平时上班
					if(rs.VacationStartDate__c.year() <=nw.year() &&
					rs.VacationStartDate__c.month() <= nw.month() && 
					rs.VacationStartDate__c.day() <= nw.day() &&
					rs.VacationEndDate__c.year() >=nw.year() &&
					rs.VacationEndDate__c.month() >= nw.month() && 
					rs.VacationEndDate__c.day() >= nw.day()  )return true;

				}

			}

			return false;

		}
		return true;

	}


    
}